package top.timous;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 * mybatis配置类
 */
@Configuration
@MapperScan(basePackages = {"top.timous.mapper"})
public class MybatisConfig {

    @Bean
    public BasicDataSource basicDataSource(){
        BasicDataSource basicDataSource = new BasicDataSource();
        basicDataSource.setUrl("jdbc:mysql://127.0.0.1:3306/practice?serverTimezone=Asia/Shanghai&amp&useSSL=false");
        basicDataSource.setUsername("root");
        basicDataSource.setPassword("123456");
        basicDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        // 数据库连接池相关操作
        basicDataSource.setInitialSize(3);  // 数据连接池的数量
        basicDataSource.setMaxActive(10);  //  最大活动数
        basicDataSource.setMaxIdle(1);   // 连接最大的空闲数量
        basicDataSource.setMaxWait(4000);   //连接的超时时间
        basicDataSource.setDefaultAutoCommit(true);
        return basicDataSource;
    }
    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource){
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        //设置实体类的别名  UserInfo
        factoryBean.setTypeAliasesPackage("top.timous.pojo");
        factoryBean.setDataSource(dataSource);
        //如果有多个的同名的类 ， 就会使用长的名称
        //创建一个配置对象 ， 该对象可以设置实体类中的成员变量与数据库的对应关系
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        // 数据库的对应字段的下划线取消 ，  后面的第一个字母大写
        configuration.setMapUnderscoreToCamelCase(true);
        factoryBean.setConfiguration(configuration);
        SqlSessionFactory sessionFactory = null;
        try {
            sessionFactory = factoryBean.getObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sessionFactory;
    }


}
